<template>
  <div class="image-upload-container">
    <a-input
      v-model:value="imageUrl"
      :placeholder="placeholder"
      @change="handleInputChange"
    >
      <template #addonAfter>
        <a-upload
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :custom-request="handleUpload"
          accept="image/*"
        >
          <a-button type="link" :loading="uploading">
            <UploadOutlined />
            {{ uploading ? '上传中...' : '选择图片' }}
          </a-button>
        </a-upload>
      </template>
    </a-input>
    
    <!-- 图片预览 -->
    <div v-if="imageUrl" class="image-preview">
      <a-image :width="120" :src="imageUrl" />
      <a-button
        type="text"
        danger
        size="small"
        @click="handleRemove"
        class="remove-btn"
      >
        <DeleteOutlined />
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import type { UploadRequestOption } from 'ant-design-vue/es/upload/interface'
import { uploadImage } from '@/api/upload'

interface Props {
  modelValue?: string
  placeholder?: string
}

interface Emits {
  (e: 'update:modelValue', value: string): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '请输入图片URL或点击上传'
})

const emit = defineEmits<Emits>()

const imageUrl = ref(props.modelValue)
const uploading = ref(false)

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  imageUrl.value = newVal
})

// 输入框变化
const handleInputChange = () => {
  emit('update:modelValue', imageUrl.value)
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('图片大小不能超过 10MB!')
    return false
  }
  
  return true
}

// 自定义上传
const handleUpload = async (options: UploadRequestOption) => {
  const { file } = options
  
  uploading.value = true
  try {
    const url = await uploadImage(file as File)
    imageUrl.value = url
    emit('update:modelValue', url)
    message.success('上传成功!')
  } catch (error) {
    console.error('上传失败:', error)
    message.error('上传失败，请重试')
  } finally {
    uploading.value = false
  }
}

// 移除图片
const handleRemove = () => {
  imageUrl.value = ''
  emit('update:modelValue', '')
}
</script>

<style scoped>
.image-upload-container {
  width: 100%;
}

.image-preview {
  margin-top: 12px;
  position: relative;
  display: inline-block;
}

.remove-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #ff4d4f;
  color: #fff;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-btn:hover {
  background: #ff7875;
  color: #fff;
}
</style>

